<?php

namespace app\common\services;

use app\common\model\EtfCodeDay;
use app\common\model\EtfLists;
use support\Cache;
use support\facade\Logger;

class EtfDataService
{
    private $host = 'https://www.tick.ai/etf/';
    static public $instance = null;

    static function getEtfListNumber(){
        $key = 'getEtfListNumber';
        $num2 = Cache::get('etfListCount');
        if(!$num2){
            $num2 = EtfLists::count();
            Cache::set('etfListCount',$num2,3600);
        }
        return $num2;
    }

    // 定时脚本 获取历史的数据  1分钟一次
    // \app\common\services\EtfDataService::getOldEtfList()
    static function getOldEtfList(){
        $today = date('Y-m-d');
        $info = EtfLists::orderBy('update_at','asc')
            ->whereRaw("update_at<'{$today}'")
            ->select(['id','code','update_at'])->first();
        if(!$info){
            return '数据今日已全部更新';
        }
        $number = self::getInstance()->chart($info->code);
        $info->update(['update_at'=>date('Y-m-d H:i:s')]);


        $where = " update_at > '{$today}' ";
        $num1 = EtfLists::whereRaw($where)->count();
        $num2 = self::getEtfListNumber();

        return "[{$info->code}]录入数据{$number}条，进度：{$num1}/{$num2}";
    }

    // 定时脚本  获取今日的etf数据  1分钟一次
    static function getDayEtfList(){
        $info = EtfLists::orderBy('update_at','asc')->select(['id','code','update_at'])->first();
        $number = self::getInstance()->chart($info->code);
        $info->update(['update_at'=>date('Y-m-d H:i:s')]);
        return "[{$info->code}]录入数据{$number}条";
    }



    static function getInstance(){
        if(self::$instance==null){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取指定etf的今日数据
     * @param $codes
     * @return void
     */
    function today($codes){
        $api = "market/chart/today?codes={$codes}";
        $data = $this->_curl($api,[],600);
        $data = $data[$codes];
        $instaData = [
            'code'=>$codes,
            'date'=>$data['date'],
            'open'=>$data['open'],// 无法获取这几个数据
            'high'=>$data['high'],
            'low'=>$data['low'],
            'close'=>$data['close'],
        ];
        EtfCodeDay::updateOrCreate([
            'code'=>$instaData['code'],
            'date'=>$instaData['date'],
        ],$instaData);
    }

    /**
     * 获取指定etf 的历史数据  只能获取到 收盘数据了
     * @param $codes
     * @return void
     */
    function chart($codes){
        $api = "market/etf/chart?code={$codes}";
        $data = $this->_curl($api,[],600);
        $data = $data['chart'];
        foreach ($data as $date =>$item){
            $instaData = [
                'code'=>$codes,
                'date'=>$date,
//                'open'=>0,// 无法获取这几个数据
//                'high'=>0,
//                'low'=>0,
                'close'=>$item[0],
            ];
            EtfCodeDay::updateOrCreate([
                'code'=>$instaData['code'],
                'date'=>$instaData['date'],
            ],$instaData);
        }
        return count($data);
    }

    /**
     * 请求接口  获取所有的etf 总览列表
     * @return void
     */
    function lists(){
        $api = "market/etf/list?avgamount=5000000-999999999999&fundtype=ETF,LOF&version=2.4.0&order=0&ordertype=1&page=1&num=100";
        $data = $this->_curl($api,[],600);
        $dataList = $data['data'];
        foreach ($dataList as $item){
            // 插入数据
            EtfLists::updateOrCreate(['code'=>$item['code']],$item);
        }
    }



    private function _curl($api,$data=[],$cache = 0){
        if($cache){
            $key = md5('etf_service_'.$api);
            $data = Cache::get($key);
            if($data) return $data;
        }
        $url = $this->host.$api;
        $op = [
            'type'=>empty($data)?'GET':'POST',
            'header'=>[
                'Content-Type:application/json',
                'User-Agent:okhttp/3.9.0',
                'Host:www.tick.ai',
                'Accept-Encoding:gzip',
            ],
            'data'=>$data,
        ];

        $res = httpRequest($url,$op,$code);
        Logger::debug("\r\n请求地址：".$url."\r\n响应内容：". $res);
        $resData = json_decode($res,1);
        $res = $resData?:$res;
        if($cache){
            // 对数据进行缓存
            Cache::set($key,$res,$cache);
        }
        return $res;
    }

}